from sqlalchemy import Column, String, Date, DateTime, func
from sqlalchemy.dialects.mysql import SMALLINT, TINYINT, DECIMAL, BIGINT
from pydantic import BaseModel
from server.model import BaseOrm
import time
import random
from os import getenv
from server import db, WeChat_pay


class PayType:
    Online = 0
    OffLineScan = 1
    OffLineCash = 2
    Package = 3


class CreateType:
    App = 0
    Admin = 1


class PurposeType:
    Booking = 0
    Charge = 1


class OrderStatus:
    Not = 0
    Paid = 1
    Cancel = 2
    Expired = 3
    Refunding = 4
    RefundFail = 5
    RefundSucceed = 6


class OrderCreate(BaseModel):
    user_id: int
    user_create: int
    payer_id: int


class OrderSchema(OrderCreate):
    id: int

    class Config:
        orm_mode = True


def create_wechat_order(body, pay_amount, open_id):
    # 商品id后2位+下单时间的年月日12+用户2后四位+随机数4位
    local_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))[2:]
    order_no = local_time + open_id[-2:] + str(random.randint(1000, 9999))
    print("got order_no", body, order_no, pay_amount, open_id)
    we_chat_order = WeChat_pay.order.create(
        trade_type="JSAPI",
        body=body,
        total_fee=pay_amount,
        notify_url=getenv('WECHAT_PAY_NOTIFY_URL'),
        user_id=open_id,
        out_trade_no=order_no
    )
    wxpay_params = WeChat_pay.jsapi.get_jsapi_params(we_chat_order.get('prepay_id'))
    return order_no, wxpay_params


def refund_wechat_order(order_no, out_refund_no, total_fee, refund_fee):
    response = WeChat_pay.refund.apply(out_trade_no=order_no,
                                       out_refund_no=out_refund_no,
                                       total_fee=total_fee,
                                       refund_fee=refund_fee,
                                       notify_url=getenv('WECHAT_REFUND_NOTIFY_URL'),
                                       )

    return response


def get_month_fee_dict():
    from server.model.m_dict import Dict
    month_fees = Dict.query.filter(Dict.name.like('%金额%')).all()
    month_fee_dict = {}
    for month_fee in month_fees:
        month_fee_dict[month_fee.name] = month_fee.content
    return month_fee_dict


def get_total_fee(subscription_type, region, months, amount):
    month_fee_dct = get_month_fee_dict()
    subscription_type_fee = month_fee_dct['每月金额']
    if subscription_type == "小记者订报":
        subscription_type_fee = month_fee_dct['小记者每月金额']
    month_fee = int(subscription_type_fee)
    if region == "其他地区":
        month_fee += 15
    print(month_fee, amount, months)
    cal_total_fee = month_fee*int(amount)*int(months)
    return cal_total_fee


# 订单
class Order(BaseOrm):
    __tablename__ = 'm_order'
    region = Column(String(32), nullable=False, server_default='', comment="寄报地区")
    province_city = Column(String(127), nullable=False, server_default='', comment="地址")
    address = Column(String(127), nullable=False, server_default='', comment="详细住址")
    postcode = Column(String(8), nullable=False, server_default='', comment="邮编")
    receiver = Column(String(32), nullable=False, server_default='', comment="收货人")
    phone = Column(String(16), nullable=False, server_default='', comment="联系电话")
    remark = Column(String(127, ), nullable=False, server_default='', comment="订单备注")
    start_date = Column(Date, comment="起始日期")
    end_date = Column(Date, comment="结束日期")
    amount = Column(SMALLINT(unsigned=True), nullable=False, server_default='0', comment="报纸数量")
    charge_standard = Column(String(255), nullable=False, server_default='', comment="收费标准")
    buyer = Column(String(32), nullable=False, server_default='', comment="购买主体")
    security_code = Column(String(4), nullable=False, server_default="", comment="验证码")
    pay_status = Column(TINYINT(unsigned=True), nullable=False, server_default='0', comment="0未支付，1已支付，2支付取消，3支付失败 ,4退款中，5退款失败，6退款成功")
    express_status = Column(TINYINT(unsigned=True), nullable=False, server_default='0', comment="0未发货，1已发货")
    total_fee = Column(DECIMAL(11, 2), server_default="0", nullable=False, comment="总金额")
    actual_paid = Column(BIGINT(20), server_default="0", nullable=False, comment="实际付款金额：分")
    body = Column(String(64), nullable=False, server_default='', comment="商品描述")
    order_no = Column(String(64), index=True, nullable=False, server_default='', comment="微信订单号")
    user_id = Column(BIGINT(20, unsigned=True), index=True, nullable=True, comment="用户id")
    subscription_type = Column(String(32), nullable=False, server_default='', comment="普通订报，小记者订报")
    school = Column(String(64), nullable=False, server_default='', comment="学校")
    classes = Column(String(32), nullable=False, server_default='', comment="班级")
    student_name = Column(String(32), nullable=False, server_default='', comment="学生姓名")


db.create_all()
